--[[
FilePath: \Lua\View\UIActivityCenter\UIActivityListShop.lua
周期兑换- 活动礼包 
--]]

require 'View/UIBase/UIBase'

UIActivityListShop = UIBase.New(PanelResNames.UIActivityListShop)
local _M = UIActivityListShop

_M.hasInit = false
_M.activeId = nil
_M.ContentItems = {}
_M.playEffect = false
_M.activityTabConfig = nil
_M.RoleLihui = nil
_M.showTimeMode = nil   --1,普通活动 2，春节活动

function _M.Init(func, id)
    _M.activeId = id
    UIBase.Init(_M, func)
end

function _M:OnCreate()
    if not _M.hasInit then
        self:RegisterOnClick(self:GetChild("Backbtn"), self.OnBack)
        self.btnHelp = self:GetChild("help")
        self.banner = self:GetChild("bannerBg")
        self.TopPic = self:GetChild("TopPic")

        self.activityTitleIcon = self:GetChild("activityTitleIcon")
        self.bgChunjieTop = self:GetChild("BG_chunjie_top")
        self.bgChunjieMid = self:GetChild("BG_chunjie_mid")
        self.bgChunjieDown = self:GetChild("BG_chunjie_down")
        self.bgChunjieHero = self:GetChild("BG_chunjie_Hero")
        self.txtChunjieTips = self:GetChild("ActivityTips")

        --self.bannerChar = self:GetChild("bannerChar")
        self.title = self:GetChild("n18"):GetChild("title")
        self.itemList = self:GetChild("list")
        self.CashLb = self:GetChild("CashLb");
        self.CoinLb3 = self:GetChild("CoinLb3");
        self.CoinLb = self:GetChild("CoinLb");
        self.lihui = self:GetChild("lihui");
        self.lihui2 = self:GetChild("lihui2");
        self.heroIcon = self:GetChild("HeroIcon");
        self.tipTime = self:GetChild("tipTime");
        self.DrawBtn = self:GetChild("DrawBtn");
        if self.activeId ~= nil then
            _M.activityTabConfig = G.dataTable["t_activitylist"][tostring(self.activeId)];
            self.activeConfigModel = G.dataTable[tostring(_M.activityTabConfig.f_ModelName)][tostring(self.activeId)];
        end
        self.DrawBtn.visible = self.activeConfigModel.f_Functionswitchid ~= 0;
        local list = TablePool.Get()
        string_split(self.activeConfigModel.f_spine,"/", list)
        if #self.activeConfigModel.f_spine > 0 then
            self._package = "FUI/"..list[1];
            if not UIPackage.GetById(self._package) then
                AddUIPackageDepend(PanelNames.UIActivityListShop, self._package)
            else
                self._package = nil;
            end
        else
            self._package = nil;
        end
        TablePool.Release(list)

        self.itemList.itemRenderer = self.RefreshItem;

        self:addEvent()
        self:InitView()
        _M.hasInit = true
    end
end

function _M:addEvent()
    self.btnHelp.onClick:Add(self.HelpTip)
    self:RegisterOnClick(self.DrawBtn,  self.OnClickDraw)
    self:RegisterEvent(Config.EventType.Fresh_Active,self.RefreshActive);
end

function _M:removeEvent()
    self.btnHelp.onClick:Remove(self.HelpTip)
end

function _M.HelpTip()
    if _M.activeConfigModel ~= nil and _M.activeConfigModel.f_ExplainTitle ~= nil and _M.activeConfigModel.f_ExplainText ~= nil then
        logicMgr.UIShowManager.ShowCommonTips(tostring(_M.activeConfigModel.f_ExplainTitle), tostring(_M.activeConfigModel.f_ExplainText));
    end
end

function _M:OnClickDraw()
    logicMgr.FuncOpenManager.jump(self.activeConfigModel.f_Functionswitchid, true);
    self:OnBack()
end

-- 显示
function _M:OnEnable()
    self.playEffect = true;
    self:Refresh();
end

function _M:InitView()
    if self.activeConfigModel ~= nil then
        if self.activeConfigModel.f_Banner ~= nil and self.activeConfigModel.f_Banner ~= "" then
            self.banner.url = self.activeConfigModel.f_Banner;
        end
        if self.activeConfigModel.f_activityTitleIcon ~= nil and self.activeConfigModel.f_activityTitleIcon ~= "" then
            self.activityTitleIcon.url = self.activeConfigModel.f_activityTitleIcon;
        end
        if self.activeConfigModel.f_chunjietop ~= nil and self.activeConfigModel.f_chunjietop ~= "" then
            self.bgChunjieTop.url = self.activeConfigModel.f_chunjietop;
        end
        if self.activeConfigModel.f_chunjiemid ~= nil and self.activeConfigModel.f_chunjiemid ~= "" then
            self.bgChunjieMid.url = self.activeConfigModel.f_chunjiemid;
        end
        if self.activeConfigModel.f_chunjiedown ~= nil and self.activeConfigModel.f_chunjiedown ~= "" then
            self.bgChunjieDown.url = self.activeConfigModel.f_chunjiedown;
        end
        if self.activeConfigModel.f_activityHerobg ~= nil and self.activeConfigModel.f_activityHerobg ~= "" then
            self.bgChunjieHero.url = self.activeConfigModel.f_activityHerobg;
        end
        if self.activeConfigModel.f_chunjiemidTips ~= nil and self.activeConfigModel.f_chunjiemidTips ~= "" then
            self.txtChunjieTips.text = getLanguage(self.activeConfigModel.f_chunjiemidTips);
        end
        if self.activeConfigModel.f_HeroIcon and self.activeConfigModel.f_HeroIcon ~= "" then
            self.heroIcon.url = tostring(self.activeConfigModel.f_HeroIcon)
        end
        if self.activeConfigModel.f_ActivityTipsTime ~= nil and self.activeConfigModel.f_ActivityTipsTime ~= "" then
            self.showTimeMode = 1
            self.tipTime.visible = true
        else
            self.showTimeMode = 2
            self.tipTime.visible = false
        end

        self.TopPic.url = self.activeConfigModel.f_TopPic;
        self.title.text = getLanguage(self.activeConfigModel.f_ActivityName);
        self.costItemId = decodeJsonStrToTabel(self.activeConfigModel.f_CostItemId);

        self.CashLb.icon = EnumConst.AtlasPath.ItemAtlas .. G.dataTable["t_item"][tostring(self.costItemId[1])].f_Icon;
        if #self.costItemId == 1 then
            self.CoinLb3.visible = false;
        elseif #self.costItemId == 2 then
            self.CoinLb3.icon = EnumConst.AtlasPath.ItemAtlas .. G.dataTable["t_item"][tostring(self.costItemId[2])].f_Icon;
        end
        self.CoinLb.icon = EnumConst.AtlasPath.ItemAtlas .. G.dataTable["t_item"]["1"].f_Icon;

        if self.activeConfigModel.f_HeroSpine ~= nil then
            local spineType = self.activeConfigModel.f_HeroSpine[2];
            local spineName = self.activeConfigModel.f_HeroSpine[1];
            local scale = self.activeConfigModel.f_HeroSpine[4];
            if spineType and spineType == 1 then
                local imageName = logicMgr.HeroManager.GetHeroDrawingPath(spineName)
                if self.drawWrapper == nil then
                    self.drawWrapper = GoWrapper.New()
                end

                resMgr:LoadModelPrefab(imageName, function(go)
                    if(self.RoleLihui~=nil)then
                        destroyImmediate(self.RoleLihui);
                        self.RoleLihui = nil
                    end
                    self.RoleLihui = newObject(go);
                    self.RoleLihui.name = imageName;
                    Util.AddAction(self.RoleLihui,"idle1",true,0.5);
                    self.RoleLihui:AddComponent(TCanvas);
                    self.drawWrapper:SetWrapTarget(self.RoleLihui,false);
                    --local scale, location = HeroManager.GetHeroLocationResize(self.activeConfigModel.f_Hero)
                    Util.Lua_SetLocalPositionXYZ(self.RoleLihui.transform,0,0,0)
                    Util.Lua_SetLocalScaleXYZ(self.RoleLihui.transform,scale,scale,scale)
                    self.lihui:SetNativeObject(self.drawWrapper);
                end)
            elseif spineType and spineType == 2 then
                local list = TablePool.Get()
                string_split(spineName,"/",list)
                AddUIPackageDepend(PanelResNames.UIActivityListShop,"FUI/"..list[1])
                TablePool.Release(list)
                self.lihui2.url ="ui://"..spineName;
                Util.PlayAction(self.lihui2.wrapTarget, self.activeConfigModel.f_HeroSpine[3], true);
            end
        end
    end
end

function _M:RefreshActive()
    self.playEffect = false;
    self:Refresh();
end

_M.itemConfig = nil;
_M.serverDataTab = nil;
function _M:Refresh()
    if self.activeId == nil or not _M.hasInit then
        self:OnBack();
    else
        self.tableData, self.serverData = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil then
            self:OnBack();
            return;
        end
    end

    self.serverDataTab = nil;
    if self.itemConfig == nil then
        self.itemConfig = {};
        local config = G.dataTable[tostring(self.activeConfigModel.f_ItemTableName)];
        for k, v in pairs(config) do
            if tonumber(v.f_ActivityId) == tonumber(self.activeId) then
                table.insert(self.itemConfig, v)
            end
        end
    end
    table.sort(self.itemConfig, function(a, b)
        return a.f_Order < b.f_Order;
    end)

    self.itemList.numItems = #self.itemConfig;
    if self.playEffect then
        self.playEffect = false;
        HelperFunc.ListTranstionPlay(self.itemList)
    end

    local haveNum = logicMgr.ItemManager.getBagNumByTableID(1);
    self.CoinLb.title = haveNum;
    haveNum = logicMgr.ItemManager.getBagNumByTableID(tonumber(self.costItemId[1]));
    self.CashLb.title = getNumString(haveNum);
    if #self.costItemId == 2 then
        haveNum = logicMgr.ItemManager.getBagNumByTableID(tonumber(self.costItemId[2]));
        self.CoinLb3.title = getNumString(haveNum);
    end
    local time = HelperFunc.GetServerTime();
    self.endCountDown = self.serverData.endTime - time;
    self:updateActiveCountDown();
    self:TimeCall(self.updateActiveCountDown, 1000, -1);
end

function _M:updateActiveCountDown()
    if self.endCountDown == nil then
        return;
    end
    local showTimeTips = self.tipTime
    if self.showTimeMode == 2 then
        showTimeTips = self.txtChunjieTips
    end
    if self.endCountDown <= 0 then
        showTimeTips.text = getLanguage("Sys_ActivityEnd");
        self:RemoveTimeCall(self.updateActiveCountDown)
    else
        showTimeTips.text = string.format(getLanguage("Sys_ActivityTimeLeft"), HelperFunc.GetSurpTimeStr(self.endCountDown));
    end
    self.endCountDown = self.endCountDown - 1;
end

function _M:GetServerData(id)
    if self.serverData == nil or self.serverData.param == nil or self.serverData.param.buyCountMap == nil then
        return 0;
    end

    local num = self.serverData.param.buyCountMap[tostring(id)];
    if num == nil then
        return 0;
    else
        return num;
    end
end

function _M.RefreshItem(index, itemObj)
    _M:CreateItem(index, itemObj)
    local config = _M.itemConfig[index + 1];
    _M.ContentItems[index]:OnShow(config, _M:GetServerData(config.f_ItemId))
end

function _M:CreateItem(index,itemObj)
    if self.ContentItems[index] then
        return
    end
    local item = self.UIActivityListShopItem.New()
    self.ContentItems[index] = item
    item:OnCreate(itemObj,self)
end

-- 隐藏
function _M:OnDisable()

end

-- 卸载
function _M:OnDestroy()
    self:removeEvent();
    if self._package and UIPackage.GetById(self._package) then
        UIPackage.RemovePackage(self._package)
    end
    if(self.RoleLihui~=nil)then
        destroyImmediate(self.RoleLihui);
        self.RoleLihui = nil
    end
    if self.ContentItems then
        for key, value in pairs(self.ContentItems) do
            value:OnDestroy()
        end
        self.ContentItems = {}
    end
    self.itemConfig = nil;
end

-- item类
_M.UIActivityListShopItem = Class("UIActivityListShopItem",UIComponentInterface)
local _M_T = _M.UIActivityListShopItem
function _M_T:OnCreate(obj,parent)
    self.taskId = 0
    self.parent = parent
    self.fguiObj = obj
    self.isGet = false;
    self.hasNum = 0;

    self.bg = obj:GetChild("bg");
    self.mask = obj:GetChild("mask");
    self.icon = obj:GetChild("Icon");
    self.tips = obj:GetChild("Tips");
    self.sellTips = obj:GetChild("sellTips");
    self.ntext = obj:GetChild("ntext");
    self.numLimit = obj:GetChild("numLimit");
    self.numMoney = obj:GetChild("numMoney");
    self.numMoneysp = obj:GetChild("numMoneysp");
    self.state = obj:GetController("state");
    self.limit = obj:GetController("limit");
    self.isfreeController = obj:GetController("isfree");
    self.typeController = obj:GetController("type");
    self.itemIcon = obj:GetChild("ItemIcon");
    self.itemNum = obj:GetChild("ItemNum");
    self.effect_taohua_yflb = obj:GetChild("effect_taohua_yflb");
    self.fguiObj.onClick:Add(function ()
        self:ClickReward();
    end);
    
end
function _M_T:OnShow(itemConfig, bugNum)
    self.config = itemConfig;
    self.bugNum = tonumber(bugNum);
    self:Refresh()
end

function _M_T:Refresh()
    if self.config.f_RefreshType == 1 then
        self.ntext.text = getLanguage("ActivityDesc120010202");
    elseif self.config.f_RefreshType == 2 then
        self.ntext.text = getLanguage("ActivityDesc120010201");
    else
        self.ntext.text = getLanguage("SellLimit");
    end
    self.typeController.selectedIndex = 0;
    if self.config.f_Price == 0 then
        self.isfreeController.selectedIndex = 1
        self.numMoney.text = getLanguage("FreeMoney");
    else
        self.isfreeController.selectedIndex = 0
        if self.config.f_PriceType == EnumConst.CostBuyType.GOLD then
            self.typeController.selectedIndex = 1;
            self.numMoneysp.text = self.config.f_Price;
        else
            self.numMoney.text = "￥"..self.config.f_Price;
        end
    end
    self.tips.text = getLanguage(tostring(self.config.f_Name));
    self.icon.url = EnumConst.AtlasPath.ICONAtlas..self.config.f_Icon;
    self.bg.url = self.parent.activeConfigModel.f_BtnPic;
    self.mask.url = self.parent.activeConfigModel.f_BtnPic;
    if self.parent.activeConfigModel.f_spine ~= nil and self.parent.activeConfigModel.f_spine ~= "" then
        self.effect_taohua_yflb.url ="ui://"..self.parent.activeConfigModel.f_spine;
        Util.PlayAction(self.effect_taohua_yflb.wrapTarget, "idle", true);
    end

    local rewards = decodeJsonStrToTabel(self.config.f_Rewards);
    self.itemIcon.icon = EnumConst.AtlasPath.ItemAtlas .. G.dataTable["t_item"][tostring(rewards[1][1])].f_Icon;
    self.itemNum.text = "x"..rewards[1][2];
    local limit = tonumber(self.config.f_Limit);
    if limit > 0 then
        self.numLimit.text = (limit - self.bugNum).."/"..limit;
        self.limit.selectedIndex = 0
        if self.bugNum >= limit then
            self.state.selectedIndex = 1;
            self.hasNum = 0;
        else
            self.state.selectedIndex = 0;
            self.hasNum = 1;
        end
    else
        self.limit.selectedIndex = 1
    end
end

function _M_T:OnHide()

end
function _M_T:OnDestroy()
    self.fguiObj.onClick:Clear();
end

function _M_T:ClickReward()
    if self.isGet or self.hasNum <= 0 then
        return;
    end

    self.isGet = true;
    if self.config.f_PriceType == EnumConst.CostBuyType.RMB then
        logicMgr.CostManager.BuyCostType(_M.activeId, {self.config.f_ItemId}, self.config.f_ProductId, 1, 2, self.config.f_Price, nil, self);
    elseif self.config.f_PriceType == EnumConst.CostBuyType.GOLD then
        if logicMgr.ItemManager.getBagNumByTableID(CurrencyEnum.GOLD) >= self.config.f_Price then
            local rewards = decodeJsonStrToTabel(self.config.f_Rewards);
            local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop)
            pop.Init(105, function (flag)
                if flag then
                    ActivityHandler.sendReqBuyByGoldMessage(_M.activeId, 0, {self.config.f_ItemId})
                end
            end, self.config.f_Price,G.dataTable["t_item"][tostring(rewards[1][1])].f_Icon, rewards[1][2])--, logicMgr.ItemManager.GetItemName(rewards[1][1]))
        else
            UISysTips.AddMsg(getLanguage("Character_Tips7"));
        end
    end

    --costHandler.reqBuyCost(tonumber(_M.activeId), {self.config.f_ItemId}, self.config.f_ProductId, 1, 2);
    self:TimeCall(self.TimeEnd, 100);
end

function _M_T:TimeEnd()
    self:RemoveTimeCall(self.TimeEnd)
    self.isGet = false;
end

return _M;